#!/usr/bin/python3
import os
import sys
import json
import sqlite3
import tarfile
import logging
import datetime
import subprocess
from signal import signal, SIGINT
from optparse import OptionParser

sys.path.append('./pylib/')
from db import *
from ops import *
from utils import *

BUILDROOT = "/mnt/physix"
FAILURE = 1
SUCCESS = 0

def handler(signal_received, frame):
    ''' Handle SIGIN/CTRL-C '''
    print('SIGINT or CTRL-C detected. Exiting... ')
    sys.exit(0)


def main():
    if 0 != os.geteuid():
        error("User not permitted. Exiting.")
        return FAILURE

    parser = OptionParser()
    parser.add_option("-i", "--build-init", dest="physix_conf",
                      help="Initialize system build process.", metavar="")
    parser.add_option("-t", "--build-toolchain", dest="toolchain_conf",
                      help="Build temp toolchain.", metavar="")
    parser.add_option("-s", "--build-base-system", dest="base_conf",
                      help="Build the Base System. ", metavar="")
    parser.add_option("-c", "--base-system-config", dest="configure_base_conf",
                      help="Configure Base system.", metavar="")
    parser.add_option("-b", "--build-recipe", dest="build_recipe",
                      help="Build Recipe", metavar="")
    parser.add_option("-a", "--start", dest="start_number",
                      help="build recipe starting at line number A", metavar="")
    parser.add_option("-z", "--stop", dest="stop_number",
                      help="build recipe no further than line number Z", metavar="")
    parser.add_option("-p", "--pull-sources", dest="pull_sources",
                      help="Download sources from from/for a recipe", metavar="")
    parser.add_option("-l", "--list-stack", action="store_true", dest="list_stack",
                      help="List state of system stack", metavar="")
    parser.add_option("-L", "--list-snapshots", action="store_true", dest="list_snaps",
                      help="List state of system stack", metavar="")
    parser.add_option("-r", "--record-snapshot", dest="snapshot",
                      help="Build temp toolchain.", metavar="")
    parser.add_option("-d", "--default-snapshot", dest="defsnap",
                      help="Set Default snapshot to boot from.", metavar="")
    parser.add_option("-D", "--delete-snapshot", dest="delete_snap",
                      help="Delete snapshot from system.", metavar="")
    parser.add_option("-q", "--quiet",
                      action="store_false", dest="verbose", default=True,
                      help="don't print status messages to stdout")
    (options, args) = parser.parse_args()

    if options.physix_conf:
        sys.exit(do_physix_conf_init(options))

    if options.toolchain_conf:
        if verify_sfwr_group('01-base-toolchain', options.toolchain_conf):
            error("Invalid build flag for recipe " + str(options.toolchain_conf))
            return FAILURE
        sys.exit(do_toolchain_build(options))

    if options.base_conf:
        if verify_sfwr_group('02-base', options.base_conf):
            error("Invalid build flag for recipe " + str(options.base_conf))
            return FAILURE
        sys.exit(do_base_build(options))

    if options.configure_base_conf:
        if verify_sfwr_group('03-base-config', options.configure_base_conf):
            error("Invalid build flag for recipe " + str(options.base_conf))
            return FAILURE
        sys.exit(do_config_base(options))

    if options.build_recipe:
        if not (verify_sfwr_group('01-base-toolchain', options.build_recipe) and
                verify_sfwr_group('02-base', options.build_recipe) and
                verify_sfwr_group('03-base-config', options.build_recipe)):
            error("Invalid build flag for recipe " + str(options.build_recipe))
            return FAILURE
        sys.exit(do_build_recipe(options))

    if options.pull_sources:
        sys.exit(do_pull_sources(options))

    if options.list_stack:
        sys.exit(do_list_stack(options))

    if options.list_snaps:
        sys.exit(do_list_snapshots())

    if options.snapshot:
        sys.exit(do_snapshot(options))

    if options.defsnap:
        sys.exit(do_set_default_snapshot(options))

    if options.delete_snap:
        sys.exit(do_delete_snapshot(options))


if __name__ == '__main__':
    signal(SIGINT, handler)
    main()

